package bearworker.zxl.service.impl;

import bearworker.zxl.dao.mapper.*;
import bearworker.zxl.dao.mapper.extra.DeliveryExtraMapper;
import bearworker.zxl.entity.*;
import bearworker.zxl.entity.extra.DeliveryOrdDtlRecive;
import bearworker.zxl.entity.extra.DeliveryOrdSenderEntity;
import bearworker.zxl.entity.extra.DeliveryPreOrderReciver;
import bearworker.zxl.entity.extra.WxPayResultEntity;
import bearworker.zxl.service.DeliveryService;
import bearworker.zxl.utils.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("delivery")
public class DeliveryServiceImpl implements DeliveryService{

	private Map<String, Object> resMap = new HashMap<>();
	
	private Logger logger = Logger.getLogger(DeliveryServiceImpl.class);
	
	@Autowired
	private DeliveryUserInfoMapper userInfoMapper;
	
	@Autowired
	private DeliveryUserLocationMapper userLocationMapper;
	
	@Autowired
	private DeliveryUserRealMapper userRealMapper;
	
	@Autowired
	private DeliverySenderMapper senderMapper;
	
	@Autowired
	private DeliveryRecipientsMapper recipientsMapper;
	
	@Autowired
	private DeliveryPackageFeeMapper packageFeeMapper;
	
	@Autowired
	private DeliveryPreOrderMapper preOrderMapper;
	
	@Autowired
	private DeliveryOrderMapper orderMapper;
	
	@Autowired
	private DeliveryOrderDetailsMapper orderDetailsMapper;
	
	@Autowired
	private DeliveryLogisticsInformationMapper logisticsInformationMapper;
	
	@Autowired
	private DeliveryUserRewardMapper userRewardMapper;

	@Autowired
	private DeliverySendPlaceMapper sendPlaceMapper;

	@Autowired
	private DeliveryExtraMapper deliveryExtraMapper;

	@Autowired
	private DeliveryWxpayRecordsMapper recordsMapper;

	@Autowired
	private DeliveryWxpayResultMapper wxpayResultMapper;
	
	final Base64.Decoder decoder = Base64.getDecoder();
	final Base64.Encoder encoder = Base64.getEncoder();
	
	@Override
	public Map<String, Object> getSenderList(Map<String, String> params) {
		
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String userIdStr = jsonObject.getString("userId");
        	try {
        		Integer userId = Integer.valueOf(userIdStr);
        		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        		if(userInfo == null) {
        			resMap = CommUtil.toResMap("500","用户id不正确",null);
            		return resMap;
        		}
        		List<DeliverySender> senderList = senderMapper.selectDeliverySenderList(userId);
        		resMap = CommUtil.toResMap("200","获取用户真实信息成功",senderList);
        		return resMap;
        	}catch (Exception e) {
				resMap = CommUtil.toResMap("500","用户不正确，请校验参数",null);
				return resMap;
			}
		}
		resMap = CommUtil.toResMap("500","参数不正确",null);
		return resMap;
	}
	
	@Override
	public Map<String, Object> getSender(Map<String, String> params) {
		
		String bodyStr = params.get("bodyStr");
		DeliverySender sender = new DeliverySender();
		
		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String senderIdStr = jsonObject.getString("senderId");
        	
        	if(StringUtils.isBlank(senderIdStr)) {
        		sender = senderMapper.selectDefaultSender();
        		resMap = CommUtil.toResMap("200","获取用户真实信息成功",sender);
        		return resMap;
        	}else {
        		try {
            		Integer senderId = Integer.valueOf(senderIdStr);
            		sender = senderMapper.selectByPrimaryKey(senderId);
            		if(sender != null) {
            			resMap = CommUtil.toResMap("200","获取用户真实信息成功",sender);
                		return resMap;
            		}else {
            			resMap = CommUtil.toResMap("500","该id对应的寄件人不存在",sender);
                		return resMap;
            		}
            		
            	}catch (Exception e) {
    				resMap = CommUtil.toResMap("500","寄件人id不正确，请校验参数",null);
    				return resMap;
    			}
        	}
        	
		}
		
		sender = senderMapper.selectDefaultSender();
		return resMap = CommUtil.toResMap("200","获取用户真实信息成功",sender);
	}
	
	
	@Override
	public Map<String, Object> delDeliverySender(Map<String, String> params) {
		DeliverySender sender = new DeliverySender();
		String bodyStr = params.get("bodyStr");

		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String senderIdStr = jsonObject.getString("senderId");
        	try {
        		Integer senderId = Integer.valueOf(senderIdStr);
        		sender = senderMapper.selectByPrimaryKey(senderId);
        		if(sender != null) {
        			if(sender.getIsDefault().intValue() == ConstantUtil.IS_DEFAULT_SENDER) {
        				resMap = CommUtil.toResMap("500","默认寄件人不允许删除",null);
        				return resMap;
        			}else {
        				sender.setState(ConstantUtil.IS_NOT_DEFAULT_STATE);
        				senderMapper.updateByPrimaryKeySelective(sender);
        				resMap = CommUtil.toResMap("200","删除成功",null);
        				return resMap;
        			}
        		}else {
        			resMap = CommUtil.toResMap("500","该id对应的寄件人不存在",sender);
            		return resMap;
        		}
        		
        	}catch (Exception e) {
				resMap = CommUtil.toResMap("500","寄件人id不正确，请校验参数",null);
				return resMap;
			}
		}

		resMap = CommUtil.toResMap("500","参数传递错误",null);
		return resMap;
	}

	@Override
	public Map<String, Object> insDeliverySender(Map<String, String> params) {

		DeliverySender sender = new DeliverySender();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);
		
		sender.setUserId(jsonObject.getInteger("userId"));
		sender.setSenderName(jsonObject.getString("senderName"));
		sender.setSenderTelephone(jsonObject.getString("senderTelephone"));
		sender.setProvince(jsonObject.getString("province"));
		sender.setCity(jsonObject.getString("city"));
		sender.setDistrict(jsonObject.getString("district"));
		sender.setSenderAddress(jsonObject.getString("senderAddress"));
		sender.setIsDefault(ConstantUtil.IS_DEFAULT_SENDER);
		
		if(sender == null) {
			resMap = CommUtil.toResMap("500","寄件人信息丢失",null);
			return resMap;
		}
		
		if(sender.getUserId() == null) {
			resMap = CommUtil.toResMap("500","关联的用户id为空，请校验参数",null);
			return resMap;
		}
		
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(sender.getUserId());
		if(userInfo == null) {
			resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
			return resMap;
		}
		
		sender.setState(ConstantUtil.IS_DEFAULT_STATE);
		DeliverySender defaultSender = null;
		if(sender.getIsDefault().intValue() == ConstantUtil.IS_DEFAULT_SENDER) {
			defaultSender = senderMapper.selectDefaultSender();
			if(defaultSender == null) {
				senderMapper.insert(sender);
				resMap = CommUtil.toResMap("200","新增寄件人成功",sender);
				return resMap;
			}else {
				senderMapper.insert(sender);
				defaultSender.setIsDefault(ConstantUtil.IS_NOT_DEFAULT_SENDER);
				senderMapper.updateByPrimaryKeySelective(defaultSender);
				resMap = CommUtil.toResMap("200","新增寄件人成功",sender);
				return resMap;
			}
		}else {
			senderMapper.insert(sender);
			resMap = CommUtil.toResMap("200","新增寄件人成功",sender);
			return resMap;
		}
		
	}


	@Override
	public Map<String, Object> updateDeliverySender(Map<String, String> params) {
		DeliverySender sender = new DeliverySender();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		sender.setUserId(jsonObject.getInteger("userId"));
		sender.setSenderName(jsonObject.getString("senderName"));
		sender.setSenderTelephone(jsonObject.getString("senderTelephone"));
		sender.setProvince(jsonObject.getString("province"));
		sender.setCity(jsonObject.getString("city"));
		sender.setDistrict(jsonObject.getString("district"));
		sender.setSenderAddress(jsonObject.getString("senderAddress"));
		sender.setIsDefault(1);
		sender.setId(jsonObject.getInteger("id"));
		
		if(sender.getId() == null) {
			resMap = CommUtil.toResMap("500","寄件人id丢失",sender);
			return resMap;
		}
		if(sender.getUserId() == null) {
			resMap = CommUtil.toResMap("500","关联的用户id为空，请校验参数",null);
			return resMap;
		}
		
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(sender.getUserId());
		if(userInfo == null) {
			resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
			return resMap;
		}
		//寄件人姓名省市信息不可更改
		sender.setSenderName(null);
		sender.setSenderTelephone(null);
		sender.setProvince(null);
		sender.setCity(null);
		sender.setDistrict(null);
		if(sender.getIsDefault().intValue() == ConstantUtil.IS_DEFAULT_SENDER) {
			DeliverySender defaultSender = senderMapper.selectDefaultSender();
			if(sender.getId().intValue() == defaultSender.getId().intValue()) {
				senderMapper.updateByPrimaryKeySelective(sender);
				resMap = CommUtil.toResMap("200","寄件人信息更新成功",sender);
				return resMap;
			}else {
				senderMapper.updateByPrimaryKeySelective(sender);
				defaultSender.setIsDefault(ConstantUtil.IS_NOT_DEFAULT_SENDER);
				senderMapper.updateByPrimaryKeySelective(defaultSender);
				resMap = CommUtil.toResMap("200","寄件人信息更新成功",sender);
				return resMap;
			}			
		}
		else {
			senderMapper.updateByPrimaryKeySelective(sender);
			resMap = CommUtil.toResMap("200","寄件人信息更新成功",sender);
			return resMap;
		}
	}


	@Override
	public Map<String, Object> insDeliveryRecipient(Map<String, String> params) {
		DeliveryRecipients recipients = new DeliveryRecipients();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		recipients.setUserId(jsonObject.getInteger("userId"));
		recipients.setRecipientsName(jsonObject.getString("recipientsName"));
		recipients.setRecipientsTelephone(jsonObject.getString("recipientsTelephone"));
		recipients.setProvince(jsonObject.getString("province"));
		recipients.setCity(jsonObject.getString("city"));
		recipients.setDistrict(jsonObject.getString("district"));
		recipients.setRecipientsAddress(jsonObject.getString("recipientsAddress"));
		recipients.setState(ConstantUtil.IS_DEFAULT_STATE);

		if(recipients == null) {
			resMap = CommUtil.toResMap("500","收件人信息丢失",null);
			return resMap;
		}
		if(recipients.getUserId() == null) {
			resMap = CommUtil.toResMap("500","用户id丢失",null);
			return resMap;
		}
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(recipients.getUserId());
		if(userInfo == null) {
			resMap = CommUtil.toResMap("500","用户id不正确",null);
			return resMap;
		}
		recipientsMapper.insert(recipients);
		resMap = CommUtil.toResMap("200","新增收件人成功",recipients.getId());
		return resMap;
	}
	

	@Override
	public Map<String, Object> delDeliveryRecipient(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		DeliveryRecipients deliveryRecipients = new DeliveryRecipients();
		
		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String recipientIdStr = jsonObject.getString("recipientId");
        	try {
        		Integer recipientId = Integer.valueOf(recipientIdStr);
        		deliveryRecipients = recipientsMapper.selectByPrimaryKey(recipientId);
        		if(deliveryRecipients == null) {
        			resMap = CommUtil.toResMap("500","id对应的收件人不存在",null);
        			return resMap;
        		}else {
        			deliveryRecipients.setState(ConstantUtil.IS_NOT_DEFAULT_STATE);
        			recipientsMapper.updateByPrimaryKeySelective(deliveryRecipients);
        			resMap = CommUtil.toResMap("200","收件人删除成功",null);
        			return resMap;
        		}
        	}catch (Exception e) {
        		resMap = CommUtil.toResMap("500","收件人id不正确",null);
    			return resMap;
			}
        	
		}else {
			resMap = CommUtil.toResMap("500","缺少参数",null);
			return resMap;
		}
	}


	@Override
	public Map<String, Object> getDeliveryRecipientList(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		List<DeliveryRecipients> deliveryRecipientsList = null;
		
		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String userIdStr = jsonObject.getString("userId");
        	try {
        		Integer userId = Integer.valueOf(userIdStr);
        		deliveryRecipientsList = recipientsMapper.selectByUserId(userId);
        		if(deliveryRecipientsList == null) {
        			resMap = CommUtil.toResMap("500","该用户对应的收件人不存在",null);
        			return resMap;
        		}else{
        			resMap = CommUtil.toResMap("200","获取收件人",deliveryRecipientsList);
        			return resMap;
        		}
        	}catch (Exception e) {
        		resMap = CommUtil.toResMap("500","用户id不正确",null);
    			return resMap;
			}
		}else {
			resMap = CommUtil.toResMap("500","缺少必要参数",null);
			return resMap;
		}
	}

	@Override
	public Map<String, Object> getDeliveryRecipient(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		DeliveryRecipients deliveryRecipients = new DeliveryRecipients();
		
		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String recipientIdStr = jsonObject.getString("recipientId");
        	try {
        		Integer recipientId = Integer.valueOf(recipientIdStr);
        		deliveryRecipients = recipientsMapper.selectByPrimaryKey(recipientId);
        		if(deliveryRecipients == null) {
        			resMap = CommUtil.toResMap("500","id对应的收件人不存在",null);
        			return resMap;
        		}else {
        			resMap = CommUtil.toResMap("200","收件人获取成功",deliveryRecipients);
        			return resMap;
        		}
        	}catch (Exception e) {
        		resMap = CommUtil.toResMap("500","收件人id不正确",null);
    			return resMap;
			}
        	
		}else {
			resMap = CommUtil.toResMap("500","缺少参数",null);
			return resMap;
		}
	}

	@Override
	public Map<String, Object> updDeliveryRecipient(Map<String, String> params) {
		DeliveryRecipients recipients = new DeliveryRecipients();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		recipients.setUserId(jsonObject.getInteger("userId"));
		recipients.setRecipientsName(jsonObject.getString("recipientsName"));
		recipients.setRecipientsTelephone(jsonObject.getString("recipientsTelephone"));
		recipients.setProvince(jsonObject.getString("province"));
		recipients.setCity(jsonObject.getString("city"));
		recipients.setDistrict(jsonObject.getString("district"));
		recipients.setRecipientsAddress(jsonObject.getString("recipientsAddress"));
		recipients.setId(jsonObject.getInteger("id"));
		recipients.setState(ConstantUtil.IS_DEFAULT_STATE);

		if(recipients == null) {
			resMap = CommUtil.toResMap("500","收件人信息丢失",null);
			return resMap;
		}
		if(recipients.getId() == null) {
			resMap = CommUtil.toResMap("500","收件人id丢失",null);
			return resMap;
		}
		if(recipients.getUserId() == null) {
			resMap = CommUtil.toResMap("500","用户id丢失",null);
			return resMap;
		}
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(recipients.getUserId());
		if(userInfo == null) {
			resMap = CommUtil.toResMap("500","用户id不正确",null);
			return resMap;
		}
		recipientsMapper.updateByPrimaryKeySelective(recipients);
		resMap = CommUtil.toResMap("200","收件人更新成功",recipients);
		return resMap;
	}

	@Override
	public Map<String, Object> deliveryShare(Map<String, String> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> getPersonalOrders(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");

		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	Integer userId = jsonObject.getInteger("userId");
			List<DeliveryOrder> orderList  = orderMapper.selectByUserId(userId);
			resMap = CommUtil.toResMap("200","我的订单获取成功",orderList);
		}else {
			resMap = CommUtil.toResMap("500", "缺少必要参数", null);
		}
		return resMap;
	}

	@Override
	public Map<String, Object> getPersonalOrderDetail(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");

		if(StringUtils.isNotBlank(bodyStr)) {
    		
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	Integer orderId = jsonObject.getInteger("orderId");
			List<DeliveryOrdDtlRecive> orderDetails = deliveryExtraMapper.getOrdDtlRecive(orderId);
			resMap = CommUtil.toResMap("200","订单详情获取成功",orderDetails);
		}else {
			resMap = CommUtil.toResMap("500", "缺少必要参数", null);
		}
		return resMap;
	}

	@Override
	public Map<String, Object> getPersonalPackages(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	Integer userId = jsonObject.getInteger("userId");

			List<DeliveryOrdDtlRecive> packageList = deliveryExtraMapper.getPackageByUserId(userId);

			resMap = CommUtil.toResMap("200","包裹列表获取成功",packageList);
        }else {
			resMap = CommUtil.toResMap("500", "请校验参数", null);
		}
		return resMap;
		
	}

	@Override
	public Map<String, Object> insPersonalOrderPre(Map<String, String> params) {
		
		Map<String, Object> resultDataMap = new HashMap<String ,Object>();
		//预订单处理
		DeliveryPreOrder preOrder = new DeliveryPreOrder();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		preOrder.setSenderId(jsonObject.getInteger("senderId"));
		preOrder.setRecipientsId(jsonObject.getInteger("recipientId"));
		preOrder.setPackageKilo(jsonObject.getDouble("packageKilo"));

		DeliverySender sender = senderMapper.selectByPrimaryKey(preOrder.getSenderId());
		DeliveryRecipients recipients = recipientsMapper.selectByPrimaryKey(preOrder.getRecipientsId());

		DeliveryPackageFee packageFee = packageFeeMapper.selectBySendProvinceAndWeight(sender.getProvince(),recipients.getProvince(),preOrder.getPackageKilo().intValue());

		preOrder.setOriginalPrice(packageFee.getRetailPrice());

		DeliveryPreOrder preOrder1 = preOrderMapper.selectByWhere(preOrder.getSenderId(),preOrder.getRecipientsId());

		if(preOrder1 != null){
			preOrder1.setOriginalPrice(preOrder.getOriginalPrice());
			preOrder1.setPackageKilo(preOrder.getPackageKilo());
			preOrderMapper.updateByPrimaryKey(preOrder1);
			preOrder.setId(preOrder1.getId());
		}else{
			preOrderMapper.insert(preOrder);
		}

		resultDataMap.put("DeliveryPreOrder", preOrder);

		resMap = CommUtil.toResMap("200","预订单处理成功",resultDataMap);
		return resMap;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRES_NEW)
	public Map<String, Object> insPersonalOrder(Map<String, String> params) {
		Map<String, Object> resultDataMap = new HashMap<String ,Object>();
		//订单处理
		DeliveryOrder order = new DeliveryOrder();

		List<DeliveryOrderDetails> list = new ArrayList<>();

		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		Integer senderId = jsonObject.getInteger("senderId");

		List<DeliveryPreOrder> preOrders = preOrderMapper.selectBySenderId(senderId);
		DeliverySender sender = senderMapper.selectByPrimaryKey(senderId);
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(sender.getUserId());



		int totalFee = 0;
		for(DeliveryPreOrder preOrder : preOrders){
			DeliveryOrderDetails orderDetails = new DeliveryOrderDetails();
			orderDetails.setOriginalPrice(preOrder.getOriginalPrice());
			orderDetails.setPackageKilo(preOrder.getPackageKilo());
			orderDetails.setRecipientsId(preOrder.getRecipientsId());
			orderDetails.setPreOrdId(preOrder.getId());
			list.add(orderDetails);
			totalFee += preOrder.getOriginalPrice();
		}

		order.setOrderNo(getOrderNo());
		order.setState(1);
		order.setDiscountPrice(0);
		order.setDiscountWayId(0);
		order.setSenderId(senderId);
		order.setOriginalPrice(totalFee);
		order.setPayPrice(totalFee);

		int res = orderMapper.insert(order);

		for(DeliveryOrderDetails orderDetails : list){
			orderDetails.setOrderId(order.getId());
			orderDetailsMapper.insert(orderDetails);
		}

		DeliveryWxpayRecords records = WxUtil.wxPay("pro","鲜速生活-快递费("+order.getOriginalPrice()/100+"元)",order.getOrderNo(),order.getOriginalPrice(),userInfo.getOpenId());

		recordsMapper.insert(records);

		resultDataMap.put("timeStamp",records.getJsTimestamp());
		resultDataMap.put("nonceStr",records.getNonceStr());
		resultDataMap.put("package",records.getJsPackage());
		resultDataMap.put("signType",records.getJsSigntype());
		resultDataMap.put("paySign",records.getJsSign());
		resultDataMap.put("orderId",order.getId());

		resMap = CommUtil.toResMap("200","创建订单成功",resultDataMap);

		for(DeliveryPreOrder preOrder : preOrders){
			preOrderMapper.deleteByPrimaryKey(preOrder.getId());
		}

		return resMap;
	}

	@Override
	public Map<String, Object> getLogistics(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String courierNumber = jsonObject.getString("courier_number");
        	if(StringUtils.isBlank(courierNumber)) {
        		resMap = CommUtil.toResMap("500","快递单号为空",null);
        		return resMap;
        	}
        	List<DeliveryLogisticsInformation> logisticsInformationList = 
        			logisticsInformationMapper.selectBycourierNumber(courierNumber);
        	resMap = CommUtil.toResMap("200","物流信息获取成功",logisticsInformationList);
    		return resMap;
        }
		resMap = CommUtil.toResMap("500","请校验参数",null);
		return resMap;
	}

	@Override
	public Map<String, Object> saveUserInfo(Map<String, String> params) {
		
		DeliveryUserInfo deliveryUserInfo = new DeliveryUserInfo();
			
		String bodyStr = params.get("bodyStr");

		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		String code = jsonObject.getString("code");

		Map<String,String> codeMap = WxUtil.proGetSession(code);

		deliveryUserInfo.setOpenId(codeMap.get("openId"));
		deliveryUserInfo.setUnionId(codeMap.get("unionId"));
		deliveryUserInfo.setNickName(jsonObject.getString("nickName"));
		deliveryUserInfo.setAvatarUrl(jsonObject.getString("avatarUrl"));
		deliveryUserInfo.setGender(jsonObject.getInteger("gender"));
		deliveryUserInfo.setCity(jsonObject.getString("city"));
		deliveryUserInfo.setProvince(jsonObject.getString("province"));
		deliveryUserInfo.setCountry(jsonObject.getString("country"));
		deliveryUserInfo.setLanguage(jsonObject.getString("language"));


		if(deliveryUserInfo == null){
			logger.error("用户信息转化失败，请校验参数");
			resMap = CommUtil.toResMap("500","用户信息转化失败，请校验参数",null);
			return resMap;
		}

		//根据unionid查询数据库是否存在用户，存在则更新，不存在则插入
		DeliveryUserInfo infoBak = userInfoMapper.selectByOpenId(deliveryUserInfo.getOpenId());

		if(infoBak != null) {
			deliveryUserInfo.setId(infoBak.getId());
		}

//		byte[] nickNameByte;
//		String nickNameStr="";
//		try {
//			nickNameByte = deliveryUserInfo.getNickName().getBytes("UTF-8");
//			nickNameStr = encoder.encodeToString(nickNameByte);
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		deliveryUserInfo.setNickName(nickNameStr);

		if(deliveryUserInfo.getId() != null) {
			userInfoMapper.updateByPrimaryKeySelective(deliveryUserInfo);
		}else {
			userInfoMapper.insert(deliveryUserInfo);
		}
		resMap = CommUtil.toResMap("200","用户信息保存成功",deliveryUserInfo.getId());
		return resMap;
	}

	@Override
	public Map<String, Object> insUserLocal(Map<String, String> params) {
		
		DeliveryUserLocation deliveryUserLocal = new DeliveryUserLocation();

		String bodyStr = params.get("bodyStr");

		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		deliveryUserLocal.setUserId(jsonObject.getInteger("userId"));
		deliveryUserLocal.setLatitude(jsonObject.getDouble("latitude"));
		deliveryUserLocal.setLongitude(jsonObject.getDouble("longitude"));
		deliveryUserLocal.setSpeed(jsonObject.getDouble("speed"));
		deliveryUserLocal.setAccuracy(jsonObject.getDouble("accuracy"));
		deliveryUserLocal.setAltitude(jsonObject.getDouble("altitude"));
		deliveryUserLocal.setVerticalaccuracy(jsonObject.getDouble("verticalAccuracy"));
		deliveryUserLocal.setHorizontalaccuracy(jsonObject.getDouble("horizontalAccuracy"));

		if(deliveryUserLocal != null) {
			if(deliveryUserLocal.getUserId() == null) {
				resMap = CommUtil.toResMap("500","用户id丢失",null);
				return resMap;
			}
			DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(deliveryUserLocal.getUserId());
			if(userInfo == null) {
				resMap = CommUtil.toResMap("500","用户id不正确",null);
				return resMap;
			}
			userLocationMapper.insert(deliveryUserLocal);	
			resMap = CommUtil.toResMap("200","用户位置保存成功",deliveryUserLocal);
			return resMap;
		}else {
			resMap = CommUtil.toResMap("500","用户位置转化失败，请校验参数",null);
			return resMap;
		}
	}

	@Override
	public Map<String, Object> insUserReal(Map<String, String> params) {
		
		DeliveryUserReal userReal = new DeliveryUserReal();			
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		userReal.setUserId(jsonObject.getInteger("userId"));
		userReal.setRealName(jsonObject.getString("realName"));
		userReal.setIdentityCard(jsonObject.getString("idNO"));
		userReal.setIdentityCardFront(jsonObject.getString("upposipic"));
		userReal.setIdentityCardBack(jsonObject.getString("upoppopic"));

		if(userReal == null) {
			logger.error("用户信息转化失败，请校验参数");
			resMap = CommUtil.toResMap("500","用户真实信息转化失败，请校验参数",null);
			return resMap;
		}
		
		//关联的用户id为空，则返回错误信息
		if(userReal.getUserId() == null) {
			resMap = CommUtil.toResMap("500","关联的用户id为空，请校验参数",null);
			return resMap;
		}
		
		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userReal.getUserId());
		if(userInfo == null) {
			resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
			return resMap;
		}
		
		DeliveryUserReal userRealBak = userRealMapper.selectByUserId(userReal.getUserId());
		if(userRealBak != null) {
			resMap = CommUtil.toResMap("500","用户实名制信息已存在，请勿重复提交",null);
			return resMap;
		}

		userRealMapper.insert(userReal);
		resMap = CommUtil.toResMap("200","用户真实信息保存成功",null);
		return resMap;
	}

	@Override
	public Map<String, Object> getUserReal(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String userIdStr = jsonObject.getString("userId");
        	
        	try {
        		Integer userId = Integer.valueOf(userIdStr);
        		DeliveryUserReal userReal = userRealMapper.selectByUserId(userId);
        		resMap = CommUtil.toResMap("200","获取用户真实信息成功",userReal.getId());
        		return resMap;
        	}catch (Exception e) {
				resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
				return resMap;
			}
        }
		resMap = CommUtil.toResMap("500","请校验参数",null);
		return resMap;
	}

	@Override
	public Map<String, Object> getOpenIdAndUnionId(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String appid = "wxdde13837f29dfceb";
        	String secret = "c1f754c8f1d4dc8515ab6c44aa3ba17c";
        	String js_code = jsonObject.getString("js_code");
        	String grant_type = jsonObject.getString("grant_type");
        	
        	if(StringUtils.isBlank(js_code)) {
        		resMap = CommUtil.toResMap("500","js_code为空",null);
        		return resMap;
        	}
        	if(StringUtils.isBlank(grant_type)) {
        		resMap = CommUtil.toResMap("500","grant_type为空",null);
        		return resMap;
        	}
        	String url = "https://api.weixin.qq.com/sns/jscode2session";
        	String param = "appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type="+grant_type;
        	String resultStr = RequestUtil.sendGet(url,param);
        	System.out.println("resultStr:"+resultStr);
        	JSONObject resultJsonObject = JSONObject.parseObject(resultStr);
        	String openId = resultJsonObject.getString("openid");
        	String unionId = resultJsonObject.getString("unionid");
        	String sessionKey = resultJsonObject.getString("session_key");
        	resultMap.put("openId", DecryptUtil.encodeOpenIdOrUnionId(openId));
        	resultMap.put("unionId", DecryptUtil.encodeOpenIdOrUnionId(unionId));
        	resultMap.put("sessionKey", DecryptUtil.encodeOpenIdOrUnionId(sessionKey));
        	resMap = CommUtil.toResMap("200","openid以及unionid获取成功",resultMap);
    		return resMap;
		}
		resMap = CommUtil.toResMap("500","缺少必要参数",null);
		return resMap;
	}

	@Override
	public Map<String, Object> getPackageFee(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
			String sendProvince = jsonObject.getString("sendProvince");
//			String sendCity = jsonObject.getString("sendCity");
//			String sendDistrict = jsonObject.getString("sendDistrict");
			String receiveProvince = jsonObject.getString("receiveProvince");
//			String receivCity = jsonObject.getString("receivCity");
//			String receiveDistrict = jsonObject.getString("receiveDistrict");
			if (StringUtils.isBlank(sendProvince)||StringUtils.isBlank(receiveProvince)) {
				resMap = CommUtil.toResMap("500","地址参数不全！",null);
				return resMap;
			}
//			DeliveryPackageFee packageFee = packageFeeMapper.selectByArea(sendProvince, receiveProvince);
//			resMap = CommUtil.toResMap("200","获取快递计费对象成功！",packageFee);
			return resMap;
		}
		resMap = CommUtil.toResMap("500","缺少必要参数！",null);
		return resMap;

	}
	
	public String getOrderNo() {
		Date date = new Date();
		String timestamp = String.valueOf(date.getTime()/1000);
		String randomStr = String.valueOf((int)((Math.random()*9+1)*100000));
		return timestamp + randomStr;
	}

	@Override
	public Map<String, Object> getUserReward(Map<String, String> params) {
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String userIdStr = jsonObject.getString("userId");
        	
        	try {
        		Integer userId = Integer.valueOf(userIdStr);
        		List<DeliveryUserReward> userRewardList = userRewardMapper.selectByUserId(userId);
        		resMap = CommUtil.toResMap("200","获取用户真实信息成功",userRewardList);
        		return resMap;
        	}catch (Exception e) {
				resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
				return resMap;
			}
        }
		resMap = CommUtil.toResMap("500","请校验参数",null);
		return resMap;
	}

	@Override
	public Map<String, Object> expressDelivery(Map<String, String> params) {
		Map<String, Object> resultDataMap = new HashMap<String, Object>();
		String bodyStr = params.get("bodyStr");
		if(StringUtils.isNotBlank(bodyStr)) {	
			JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        	String userIdStr = jsonObject.getString("userId");
        	if(StringUtils.isBlank(userIdStr)) {
        		resMap = CommUtil.toResMap("500","用户id为空",null);
        		return resMap;
        	}
        	try {
        		Integer userId = Integer.valueOf(userIdStr);
        		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        		if(userInfo == null) {
        			resMap = CommUtil.toResMap("500","用户id不正确",null);
            		return resMap;
        		}
        		resultDataMap.put("userInfo", userInfo);
        		List<DeliveryOrder> orderList = orderMapper.selectByUserIdAndState(userId, ConstantUtil.IS_ORDER_NO_PAY);
        		resultDataMap.put("orderList", orderList);
        		resMap = CommUtil.toResMap("200","获取收快递信息成功",resultDataMap);
        		return resMap;
        	}catch (Exception e) {
				resMap = CommUtil.toResMap("500","用户id不正确，请校验参数",null);
				return resMap;
			}
        }
		resMap = CommUtil.toResMap("500","请校验参数",null);
		return resMap;
	}

	public Map<String, Object> getSendPlace(Map<String, String> params){
		String bodyStr = params.get("bodyStr");

		List<DeliverySendPlace> sendPlace = sendPlaceMapper.selectAll();

		resMap = CommUtil.toResMap("200","获取发送地区成功",sendPlace.get(0));
		return resMap;
	}

	public Map<String, Object> getSenderOrdPre(Map<String, String> params){
		Map<String, Object> resultDataMap = new HashMap<String, Object>();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);
		Integer senderId = jsonObject.getInteger("senderId");

		List<DeliveryPreOrderReciver> preOrderList = deliveryExtraMapper.getSenderRePreOrd(senderId);

		resMap = CommUtil.toResMap("200","获取预订单成功",preOrderList);
		return resMap;
	}

	public Map<String, Object> delPreOrder(Map<String, String> params){
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);

		Integer senderId = jsonObject.getInteger("senderId");
		Integer recipentId = jsonObject.getInteger("recipentId");

		DeliveryPreOrder preOrder = preOrderMapper.selectByWhere(senderId,recipentId);

		if(preOrder != null){
			preOrderMapper.deleteByPrimaryKey(preOrder.getId());
			resMap = CommUtil.toResMap("200","删除成功",null);
		}else {
			resMap = CommUtil.toResMap("200","无预订单数据",null);
		}

		return resMap;
	}

	public String paynotify(Map<String, String> params){
		WxPayResultEntity resultEntity = new WxPayResultEntity();
		DeliveryWxpayResult wxpayResult = new DeliveryWxpayResult();
		logger.debug(params.get("bodyStr"));
		String resXml = params.get("bodyStr");

		Map<String,String> resMap = XmlUtil.xmltoMap(resXml);

		wxpayResult.setAppid(resMap.get("appid"));
		wxpayResult.setBankType(resMap.get("bank_type"));
		wxpayResult.setCashFee(resMap.get("cash_fee"));
		wxpayResult.setFeeType(resMap.get("fee_type"));
		wxpayResult.setIsSubscribe(resMap.get("is_subscribe"));
		wxpayResult.setMchId(resMap.get("mch_id"));
		wxpayResult.setNonceStr(resMap.get("nonce_str"));
		wxpayResult.setOpenid(resMap.get("openid"));
		wxpayResult.setOutTradeNo(resMap.get("out_trade_no"));
		wxpayResult.setResultCode(resMap.get("result_code"));
		wxpayResult.setReturnCode(resMap.get("return_code"));
		wxpayResult.setSign(resMap.get("sign"));
		wxpayResult.setTimeEnd(resMap.get("time_end"));
		wxpayResult.setTotalFee(resMap.get("total_fee"));
		wxpayResult.setTradeType(resMap.get("trade_type"));
		wxpayResult.setTransactionId(resMap.get("transaction_id"));

		wxpayResultMapper.insert(wxpayResult);

		DeliveryOrder order = orderMapper.selectByOrderNo(wxpayResult.getOutTradeNo());

		order.setState(ConstantUtil.IS_ORDER_PAYED);
		order.setWechatPayNo(wxpayResult.getTransactionId());

		orderMapper.updateByPrimaryKey(order);

		resultEntity.setReturn_code("SUCCESS");
		resultEntity.setReturn_msg("OK");
		String res = XmlUtil.mapToXml(resultEntity);
		logger.debug(res);
		return res;
	}

	public Map<String, Object> rePay(Map<String, String> params){
		Map<String, Object> resultDataMap = new HashMap<String ,Object>();
		String bodyStr = params.get("bodyStr");
		JSONObject jsonObject = JSONObject.parseObject(bodyStr);
		Integer orderId = jsonObject.getInteger("orderId");

		DeliveryOrder order = orderMapper.selectByPrimaryKeyandState(orderId,ConstantUtil.IS_ORDER_NO_PAY);

		if(order != null) {
			DeliveryWxpayRecords records = recordsMapper.selectByOrderNo(order.getOrderNo());

			resultDataMap.put("timeStamp", records.getJsTimestamp());
			resultDataMap.put("nonceStr", records.getNonceStr());
			resultDataMap.put("package", records.getJsPackage());
			resultDataMap.put("signType", records.getJsSigntype());
			resultDataMap.put("paySign", records.getJsSign());
			resultDataMap.put("orderId", order.getId());

			resMap = CommUtil.toResMap("200", "订单重新付款成功", resultDataMap);
		}else {
			resMap = CommUtil.toResMap("500", "订单已关闭", null);
		}

		return resMap;
	}

	public Map<String, Object> getShareUrl(Map<String, String> params){

		logger.debug(params.get("userId"));

		int userId = Integer.valueOf(params.get("userId"));

		DeliveryUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);

		String ticket = WxUtil.userShareUrl(userInfo.getOpenId(),userId+"");

		Map<String, String> resultDataMap = new HashMap<String ,String>();

		resultDataMap.put("url","https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket);
		resultDataMap.put("nickName",userInfo.getNickName());

		resMap = CommUtil.toResMap("200", "获取分享链接成功", resultDataMap);

		return resMap;
	}

	public Map<String, Object> getWaitOrds(Map<String, String> params){
		List<DeliveryOrdSenderEntity> payedOrder = deliveryExtraMapper.getOrdByState(2);

		resMap = CommUtil.toResMap("200", "获取成功", payedOrder);

		return resMap;
	}

	@Override
	public Map<String, Object> getWaitOrdDtls(Map<String, String> params) {
		Integer ordId = Integer.valueOf(params.get("orderId"));

		List<DeliveryOrdDtlRecive> orderDetails = deliveryExtraMapper.getOrdDtlRecive(ordId);
		resMap = CommUtil.toResMap("200","订单详情获取成功",orderDetails);

		return resMap;
	}

}
